<script setup lang="ts">
import type {PickerColumn} from 'vant'
import {showConfirmDialog} from 'vant'
import router from '@/router'
import {useAppStore, useUserStore} from '@/stores'
import {languageColumns, locale} from '@/utils/i18n'

const { t } = useI18n()
const userStore = useUserStore()
const userInfo = computed(() => userStore.userInfo)
const appStore = useAppStore()
const showLanguagePicker = ref(false)
const checked = ref<boolean>(isDark.value)

const language = computed(() => languageColumns.find(l => l.value === locale.value).text)

function toggle() {
  toggleDark()
  appStore.switchMode(isDark.value ? 'dark' : 'light')
}
function Logout() {
  showConfirmDialog({
    title: t('settings.comfirmTitle'),
  })
    .then(() => {
      userStore.logout()
      router.push({ name: 'home' })
    })
    .catch(() => {
    })
}

const languageValues = ref<Array<string>>([locale.value])

function onLanguageConfirm(event: { selectedOptions: PickerColumn }) {
  locale.value = event.selectedOptions[0].value as string
  showLanguagePicker.value = false
}
</script>

<template>
  <VanCellGroup :border="false" :inset="true" :title="t('menus.basicSettings')">
    <VanCell :title="t('menus.darkMode')" center>
      <template #right-icon>
        <VanSwitch v-model="checked" aria-label="on/off Dark Mode" class="w-1/2" size="20px" @click="toggle()" />
      </template>
    </VanCell>
    <VanCell :title="t('menus.language')" :value="language" is-link @click="showLanguagePicker = true" />
  </VanCellGroup>
  <div class="text-center">
    <VanCellGroup :inset="true">
      <van-cell v-if="userInfo.userId" :title="$t('settings.logout')" class="van-text-color" clickable
        @click="Logout" />
    </VanCellGroup>

    <div class="mt-10 text-gray">
      {{ $t("settings.currentVersion") }}: v{{ version }}
    </div>

    <van-popup v-model:show="showLanguagePicker" position="bottom">
      <van-picker v-model="languageValues" :columns="languageColumns" @cancel="showLanguagePicker = false"
        @confirm="onLanguageConfirm" />
    </van-popup>
  </div>
</template>

<style scoped>
.van-text-color {
  --van-cell-text-color: var(--van-red);
}
</style>

<route lang="json5">
{
  name: 'settings',
  meta: {
    title: '我的设置',
    i18n: 'menus.settings'
  },
}
</route>
